import { createRouter, createWebHashHistory } from 'vue-router'
import { baseRoutes } from './baseRoutes'
import { authorityRoutes, initAuthorityRoutes } from './authorityRoutes'
import { useUserStore } from '../store/user'
import { deepClone } from '@/utils'

const routes: any[] = deepClone(baseRoutes)

//创建基础路由
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})

//初始化路由函数
function initRouter() {
  //清空路由
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
  //添加路由
  const baseRoutesArr = deepClone(baseRoutes)
  baseRoutesArr.forEach((r: any) => {
    router.addRoute(r)
  })

  //初始化权限路由
  initAuthorityRoutes()
  const authorityRoutesArr = deepClone(authorityRoutes)
  router.removeRoute('notFound')
  authorityRoutesArr.forEach((r) => {
    router.addRoute(r)
  })

  router.addRoute({
    path: '/:pathMatch(.*)',
    name: 'notFound',
    redirect: '/error/404'
  })
  // 返回克隆的路由，避免修改后children清空，redirect失败，栈溢出
  return [...baseRoutesArr, ...authorityRoutesArr]
}

//路由守卫
router.beforeEach((to) => {
  document.title = to.meta.title as string

  //验证token
  if (useUserStore().token === '' && to.name !== 'login') {
    return {
      path: '/login'
    }
  }
})

export { router, initRouter }
